import store2 from 'store2'
import _ from 'underscore'
let cartStore = {
  get () {
    let cart = {};
    if(store2.has('CAER_MAP')) {
      cart = JSON.parse(store2('CAER_MAP'));
    } else {
      cart = {};
      store2('CAER_MAP', JSON.stringify(cart));
    }
    return cart;
  },
  save (cart) {
    store2('CAER_MAP', JSON.stringify(cart));
  }
}
const state = {
  cart: {},
  shopId: ''
}

const getters = {
  ['getCart'] (state) {
    return state.cart
  }
}

const actions = {
  ['initCart'] ({commit,state}, shopId) {
    let cart = cartStore.get();
    if(!cart[shopId]) {
      cart[shopId] = {
        goods: []
      }
    }
    commit('updataCart', cart);
    commit('setShopId', shopId)
  },
  ['addCart'] ({commit, state}, goods) {
    let goodsList = state.cart[state.shopId] ? state.cart[state.shopId].goods : [];
    let goodsIndex = _.findIndex(goodsList, function (item) {
      if (item.haveSp) {
        return item.goSn == goods.goSn && item.spSn == goods.spSn
      } else {
        return item.goSn == goods.goSn
      }
    })
    if (goodsIndex >= 0) {
      goodsList[goodsIndex].goNum = goodsList[goodsIndex].goNum + 1
    } else {
      goodsList.push(Object.assign({
        goWeight: '',
        goDelivery: 0,
        goCustomMade: 0,
        goDeliveryDate: '',
        goMade: '',
        spSn: ''
      },goods, {
        goNum: 1,
        goContent: '',
        goMoney: goods.goPrice
      }))
    }
    commit('addCart', goodsList)
  },
  ['removeCart'] ({commit, state}, goods) {
    let goodsList = state.cart[state.shopId].goods;
    let goodsIndex = _.findIndex(goodsList, function (item) {
      if (item.haveSp) {
        return item.goSn == goods.goSn && item.spSn == goods.spSn
      } else {
        return item.goSn == goods.goSn
      }
    })
    if ( goodsList[goodsIndex].goNum>1) {
      goodsList[goodsIndex].goNum =  goodsList[goodsIndex].goNum-1
    } else {
      goodsList.splice(goodsIndex, 1);
    }
    commit('addCart', goodsList)
  },
  ['clearCart'] ({commit}, shopId) {
    commit('clearCart', shopId);
  }
}

const mutations = {
  ['updataCart'] (state, cart) {
    state.cart = cart;
  },
  ['setShopId'] (state, shopId) {
    state.shopId = shopId
  },
  ['addCart'] (state, goodsList) {
    state.cart[state.shopId] = {
      goods: goodsList
    }
    cartStore.save(state.cart)
  },
  ['clearCart'] (state, shopId) {
    state.cart[shopId] = {
      goods: []
    };
    cartStore.save(state.cart)
  }
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}
